#include "Protocol.hpp"
#include "Sock.hpp"
#include<unistd.h>
using namespace na_protocol;
static void Usage(char *proc)
{
    std::cout << "\nUsage" << proc << " server_port "
              << "server_ip" << std::endl;
}

//./ CalClient server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    uint16_t service_port = atoi(argv[2]);
    std::string service_ip = argv[1];
    Sock sock;
    int socket = sock.Socket();
    if (sock.Connect(socket, service_port, service_ip) < 0) // 与服务器建立连接
    {
        std::cerr << "connect fail" << std::endl;
        exit(2);
    }
    bool quit=false;
    while (!quit)
    {

        std::cout << "请输入#";
        int x, y;
        char op;
        std::cin >> x >> op >> y;
        Request req(x, op, y); // 构造一个计算对象

        std::string package = req.Serialize(); // 计算对象序列化
        package = Encode(package);              // 序列化后的有效信息添加报头以及SEP分隔符
         Send(socket, package);                 // 报文发送给服务器
         //std::cout<<package<<std::endl;
         //std::cout<<"send success"<<std::endl;
        std::string buffer;
        while (true)
        {
            if (!(Recv(socket, &buffer))) // 从服务器中读取计算结果  4\r\n0 59\r\n
            {
                quit=true;
                break;
            }
            std::string str = Decode(buffer);//提取计算结果的有效信息 0 59
            //std::cout<<str<<std::endl;
            if (str.empty()) // 没有提取到一条完整的信息,继续Recv读取信息
            {
                continue;
            }
            Response res;
            if(res.Deserialized(str))//对计算结果有效信息进行反序列化
           {
            switch(res._code)
            {
                case 0:
                  std::cout<<req._x<<req._op<<req._y<<"="<<res._result<<"[success]"<<std::endl;
                  break;
                case 1:
                 std::cout<<"除0错误"<<std::endl;
                 break;
                 case 2:
                 std::cout<<"模0错误"<<std::endl;
                 case 3:
                 std::cout<<"非法输入"<<std::endl;

            }

           }
           break;
        }
    }
     close(socket);
    return 0;
}